
#include "Layer.h"
#include "../../TinyXML/tinyxml.h"
#include "..\\Game Objects\\Camera.h"

Layer::Layer()
{
	vecTiles.clear();
}


Layer::~Layer()
{
	vecTiles.clear();
}

// Using this function avoids direct access to the layer's level, locX & locY are the level's coordinates
void Layer::SetTile(const Tile& tile, int locX, int locY)
{
	vecTiles[locX][locY] = tile;
}

void Layer::SetName(const std::string& name)
{
	strName = name;
}

void Layer::SetParalax(float paralax)
{
	fParalax = paralax;
}

void Layer::SetVisibility(bool vis)
{
	bVisibility = vis;
}

void Layer::InitializeTiles(int levWidth, int levHeight)
{
	vecTiles.resize(levWidth);

	for (int i = 0; i < levWidth; i++)
	{
		vecTiles[i].resize(levHeight);
	}
}

// Pass down the tile size so that it is only stored once, in the tile manager
void Layer::Render(int levWidth, int levHeight, int tileWidth, int tileHeight)
{
	Camera* camera = Camera::GetInstance();
	int x = (int)(camera->GetPosition().x / tileWidth) - 1;
	int y = (int)(camera->GetPosition().y / tileHeight) - 1;
	int eX = (int)((camera->GetPosition().x + SCREEN_WIDTH) / tileWidth) + 1;
	int eY = (int)((camera->GetPosition().y + SCREEN_HEIGHT) / tileHeight) + 1;
	if (x < 0)
		x = 0;
	if (eX > levWidth)
		eX = levWidth;
	if (y < 0)
		y = 0;
	if (eY > levHeight)
		eY = levHeight;

	for (; x < eX; ++x)
	{
		for (; y < eY; ++y)
		{
			Tile t = vecTiles[x][y];
			if (t.GetTileX() == -1)
				continue;

				vecTiles[x][y].Render(tileWidth, tileHeight, x, y);
		}
	}
}



void Layer::LoadTileSet(Sprite* sprite, int levWidth, int levHeight)
{
	for (int x = 0; x < levWidth; x++)
	{
		for (int y = 0; y < levHeight; y++)
		{
			if (vecTiles[x][y].GetTileX() != 0 || vecTiles[x][y].GetTileY() != 0)
			{
				vecTiles[x][y].SetSprite(sprite);
			}
		}
	}
}

void Layer::CheckCollisions(int levWidth, int levHeight, int tileWidth, int tileHeight, GameObject* collision)
{
	Camera* camera = Camera::GetInstance();
	int x = (int)(camera->GetPosition().x / tileWidth) - 1;
	int y = (int)(camera->GetPosition().y / tileHeight) - 1;
	int eX = (int)((camera->GetPosition().x + SCREEN_WIDTH) / tileWidth) + 1;
	int eY = (int)((camera->GetPosition().y + SCREEN_HEIGHT) / tileHeight) + 1;
	if (x < 0)
		x = 0;
	if (eX > levWidth)
		eX = levWidth;
	if (y < 0)
		y = 0;
	if (eY > levHeight)
		eY = levHeight;

	int locX = (int)collision->GetPosition().x;
	int locY = (int)collision->GetPosition().y;

	for (; x < eX; ++x)
	{
		for (; y < eY; ++y)
		{
			int testX = x * tileWidth + tileWidth * 3;
			int otherTestX = x * tileWidth;

			int testY = y * tileHeight + tileHeight * 3;
			int otherTestY = y * tileHeight;
			if ((locX <= x * tileWidth + tileWidth * 3 || locX > x * tileWidth) && (locY <= y * tileHeight + tileHeight * 3 || locY > y * tileHeight))
			{
				vecTiles[x][y].CheckCollision(x, y, tileWidth, tileHeight, collision);
			}
		}
	}
}